﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools.Domain;

namespace Tools.DA.Repository
{
    public class ContextBase : DbContext, IDbContext
    {
        public ContextBase()
        {
            ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += ObjectContext_ObjectMaterialized;
        }

        void ObjectContext_ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
        {
            var entity = e.Entity as IObjectWithState;
            if (entity != null)
            {
                entity.State = State.Unchanged;
                entity.OriginalValues = BuildOriginalValues(this.Entry(entity).OriginalValues);
            }
        }
        private static Dictionary<string, object> BuildOriginalValues(DbPropertyValues originalValues)
        {
            var result = new Dictionary<string, object>();
            foreach (var propertyName in originalValues.PropertyNames)
            {
                var value = originalValues[propertyName];
                if (value is DbPropertyValues)
                {
                    result[propertyName] = BuildOriginalValues((DbPropertyValues)value);
                }
                else
                {
                    result[propertyName] = value;
                }
            }
            return result;
        }

        public new IDbSet<TEntity> Set<TEntity>() where TEntity : EntityBase
        {
            return this.Set<TEntity>();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }
    }
}
